package com.brainshare.web.controller.an;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.brainshare.an.domain.*;
import com.brainshare.an.service.*;
import com.brainshare.an.util.AnPlatformUtil;
import com.brainshare.common.core.controller.BaseController;
import com.brainshare.common.core.domain.AjaxResult;
import com.brainshare.common.core.page.TableDataInfo;
import com.brainshare.common.utils.*;
import com.brainshare.utils.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import oshi.driver.mac.net.NetStat;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * 小程序用户接口
 *
 * @author ruoyi
 * @date 2022-11-04
 */
@RestController
@RequestMapping("/an/wechat_app")
public class AnWechatAppController extends BaseController {
    @Value("${ruoyi.profile}")
    private String rootPath;
    @Value("${ruoyi.evaluationHost}")
    private String evaluationHost;
    @Value("${ruoyi.evaluationWebViewHost}")
    private String evaluationWebViewHost;
    @Autowired
    private IAnWechatUserService anWechatUserService;
    @Autowired
    private IAnWechatUserMechanismService anWechatUserMechanismService;
    @Autowired
    private IAnMechanismService anMechanismService;
    @Autowired
    private IAnMechanismMemberService anMechanismMemberService;
    @Autowired
    private IAnCallBackService anCallBackService;

    /**
     * 查询个人信息
     */
    @GetMapping("/wechat_user/info")
    public TableDataInfo wechatUserInfo(HttpServletRequest request)
    {
        AnWechatUser anWechatUser = CommonUtils.getAnWechatUser(request);
        List<AnWechatUser> list = new ArrayList<>();
        AnWechatUser updateAnWechatUser = anWechatUserService.updateAnWechatUserInfoById(anWechatUser.getWechatUserId());
        list.add(updateAnWechatUser);
        return getDataTable(list);
    }

    /**
     * 根据身份证号计算年龄，性别
     *
     * @param request
     * @return
     */
    @GetMapping("/wechat_user/bir_age_sex")
    public AjaxResult getBirAgeSex(HttpServletRequest request) {
        String userCardId = request.getParameter("userCardId");
        Map<String, String> birAgeSex = CertificateNoUtil.getBirAgeSex(userCardId);
        return AjaxResult.success(birAgeSex);
    }

    @PostMapping("/wechat_user/update")
    public AjaxResult wechatUserUpdate(HttpServletRequest request, @RequestBody AnWechatUser anWechatUser)
    {
        AnWechatUser tokenWechatUser = CommonUtils.getAnWechatUser(request);
        anWechatUser.setWechatUserId(tokenWechatUser.getWechatUserId());
        boolean result = anWechatUserService.updateAnWechatUserInfo(anWechatUser);
        if (result)
        {
            return AjaxResult.success("更新用户信息成功！", anWechatUser);
        }
        return AjaxResult.error("更新用户信息失败！");
//        AnWechatUser tokenWechatUser = CommonUtils.getAnWechatUser(request);
//        if (tokenWechatUser == null) {
//            return AjaxResult.error("");
//        }
//        anWechatUser.setWechatUserId(tokenWechatUser.getWechatUserId());
//        anWechatUserService.updateAnWechatUser(anWechatUser);
//        AnWechatUser wechatUser = anWechatUserService.selectAnWechatUserByWechatUserId(tokenWechatUser.getWechatUserId());
//        //更新缓存
//        String token = request.getParameter("token");
//        redisTemplate.opsForValue().set("user:" + token, JSON.toJSONString(wechatUser));
//        return AjaxResult.success(wechatUser);
    }

    /**
     * 提交个人信息
     *
     * @param request
     * @return
     */
    @PostMapping("/wechat_user/submit")
    public AjaxResult wechatUserSubmit(HttpServletRequest request, @Validated @RequestBody AnWechatUser anWechatUser) {
        AnWechatUser tokenWechatUser = CommonUtils.getAnWechatUser(request);
        if (tokenWechatUser == null) {
            return AjaxResult.error("");
        }
        tokenWechatUser.setWechatUserId(tokenWechatUser.getWechatUserId());
        tokenWechatUser.setUserName(anWechatUser.getUserName());
        tokenWechatUser.setSex(anWechatUser.getSex());
        tokenWechatUser.setUserCardId(anWechatUser.getUserCardId());
        tokenWechatUser.setAge(anWechatUser.getAge());
        tokenWechatUser.setEducation(anWechatUser.getEducation());
//        tokenWechatUser.setPhone(anWechatUser.getPhone());
        tokenWechatUser.setAddress(anWechatUser.getAddress());
        tokenWechatUser.setMarriage(anWechatUser.getMarriage());
        tokenWechatUser.setOccupation(anWechatUser.getOccupation());
        tokenWechatUser.setUpdateBy("admin");
        tokenWechatUser.setUpdateTime(DateUtils.getNowDate());
        tokenWechatUser.setAddressCode(anWechatUser.getAddressCode());
        tokenWechatUser.setIpAddress(CommonUtils.getIpAddress(request));
        //推广码存在绑定推广员
        JSONObject questionData = new JSONObject();
        if (StringUtils.isNotEmpty(anWechatUser.getPromotionCode())) {
            AnMechanismMember anMechanismMember = new AnMechanismMember();
            anMechanismMember.setPromotionCode(anWechatUser.getPromotionCode());
            //设置机构名称
            List<AnMechanismMember> anMechanismMembers = anMechanismMemberService.selectAnMechanismMemberList(anMechanismMember);
            if (anMechanismMembers.size() == 0) {
                return AjaxResult.error("该推广码不存在!");
            }
            for (AnMechanismMember mechanismMember : anMechanismMembers) {
                AnMechanism anMechanism = anMechanismService.selectAnMechanismByMechanismId(mechanismMember.getMechanismId());
                tokenWechatUser.setScreeningSource(anMechanism.getMechanismName() + "-" + mechanismMember.getMemberName());
                tokenWechatUser.setMechanismId(mechanismMember.getMechanismId());
                tokenWechatUser.setMechanismMemberId(mechanismMember.getMechanismMemberId());
                //插入用户和推广员的关系
                AnWechatUserMechanism wechatUserMechanism = new AnWechatUserMechanism();
                wechatUserMechanism.setWechatUserId(tokenWechatUser.getWechatUserId());
                wechatUserMechanism.setMechanismMemberId(mechanismMember.getMechanismMemberId());
                wechatUserMechanism.setPromotionCode(anWechatUser.getPromotionCode());
                wechatUserMechanism.setAuthTime(DateUtils.getNowDate());
                wechatUserMechanism.setCreateBy("admin");
                wechatUserMechanism.setCreateTime(DateUtils.getNowDate());
                //请求平台端，获取到做题页面
                questionData = AnPlatformUtil.requestNewPlatformQuestion(tokenWechatUser);
                wechatUserMechanism.setEvaluationUrl(questionData.getString("url"));
                wechatUserMechanism.setTradeNo(questionData.getString("token"));
                wechatUserMechanism.setOutTradeNo(questionData.getString("patientId"));
                anWechatUserMechanismService.insertAnWechatUserMechanism(wechatUserMechanism);
            }
            anWechatUserService.updateAnWechatUserInfo(tokenWechatUser);
//            anWechatUserService.updateAnWechatUser(tokenWechatUser);
//            //更新缓存
//            String token = request.getParameter("token");
//            redisTemplate.opsForValue().set("user:" + token, JSON.toJSONString(tokenWechatUser));
            //返回做题页面
            return AjaxResult.success(questionData);
        } else {
            AnWechatUserMechanism wechatUserMechanism = new AnWechatUserMechanism();
            wechatUserMechanism.setWechatUserId(tokenWechatUser.getWechatUserId());
            wechatUserMechanism.setAuthTime(DateUtils.getNowDate());
            wechatUserMechanism.setCreateBy("admin");
            wechatUserMechanism.setCreateTime(DateUtils.getNowDate());
            //请求平台端，获取到做题页面
            questionData = AnPlatformUtil.requestNewPlatformQuestion(tokenWechatUser);
            wechatUserMechanism.setEvaluationUrl(questionData.getString("url"));
            wechatUserMechanism.setTradeNo(questionData.getString("token"));
            wechatUserMechanism.setOutTradeNo(questionData.getString("patientId"));
            anWechatUserMechanismService.insertAnWechatUserMechanism(wechatUserMechanism);
            anWechatUserService.updateAnWechatUserInfo(tokenWechatUser);
//            anWechatUserService.updateAnWechatUser(tokenWechatUser);
//            //更新缓存
//            String token = request.getParameter("token");
//            redisTemplate.opsForValue().set("user:" + token, JSON.toJSONString(tokenWechatUser));
            return AjaxResult.success(questionData);
        }
    }

    private JSONObject getQuestionUrl(AnWechatUserMechanism wechatUserMechanism, String outTradeNo, JSONObject object) {
        JSONObject questionData;
        JSONObject data = object.getJSONObject("data");
        data.remove("signature");
        questionData = data;
        String tradeNo = data.getString("tradeNo");
        String evaluationUrl = data.getString("evaluationUrl");
        evaluationUrl = evaluationUrl.replace(evaluationWebViewHost, "https://www.ainaoxingdong.com/webview");
        wechatUserMechanism.setTradeNo(tradeNo);
        wechatUserMechanism.setEvaluationUrl(evaluationUrl);
        wechatUserMechanism.setOutTradeNo(outTradeNo);
        questionData.put("evaluationUrl", evaluationUrl);
        questionData.put("outTradeNo", outTradeNo);
        return questionData;
    }


    /**
     * 查询机构审核状态喝信息
     */
    @GetMapping("/mechanism/info")
    public TableDataInfo mechanismInfo(HttpServletRequest request) {
        AnWechatUser anWechatUser = CommonUtils.getAnWechatUser(request);
        AnMechanism anMechanism = new AnMechanism();
        anMechanism.setWechatUserId(anWechatUser.getWechatUserId());
        List<AnMechanism> list = anMechanismService.selectAnMechanismList(anMechanism);
        return getDataTable(list);
    }

    /**
     * 查询指定报告
     */
    @GetMapping("/wechat_user/get_report")
    public AjaxResult getReport(HttpServletRequest request) {
        if (request.getParameter("mechanismMemberUserId") != null) {
            AnWechatUserMechanism anWechatUserMechanism = anWechatUserMechanismService.selectAnWechatUserMechanismByMechanismMemberUserId(Long.parseLong(request.getParameter("mechanismMemberUserId")));
            if (anWechatUserMechanism.getScreeningResult() != null) {
                JSONObject reportObj = JSONObject.parseObject(anWechatUserMechanism.getScreeningResult());
                if (reportObj.getInteger("code") != 1) {
                    return AjaxResult.error("报告不存在！");
                } else {
                    Long wechatUserId = anWechatUserMechanism.getWechatUserId();
                    AnWechatUser anWechatUser = anWechatUserService.selectAnWechatUserByWechatUserId(wechatUserId);
                    reportObj.getJSONObject("data").put("gender", anWechatUser.getSex() == 0 ? "男" : "女");
                    reportObj.put("mechanismMemberUserId", anWechatUserMechanism.getMechanismMemberUserId());
                    return AjaxResult.success(reportObj);
                }
            } else {
                return AjaxResult.error("记录不存在！");
            }
        }
        return AjaxResult.error("不存在该报告！");
    }

    /**
     * 查询用户报告
     */
    @GetMapping("/wechat_user/report")
    public AjaxResult userReport(HttpServletRequest request)
    {
        AnWechatUser anWechatUser = CommonUtils.getAnWechatUser(request);
        logger.info("1、查询用户报告" + JSON.toJSONString(anWechatUser));
        AnWechatUserMechanism queryAnWechatUserMechanism = new AnWechatUserMechanism();
        queryAnWechatUserMechanism.setWechatUserId(anWechatUser.getWechatUserId());
        logger.info("查询用户报告请求参数" + "1、" + request.getParameter("js_patientId") + "2、" + request.getParameter("js_token"));
        if (request.getParameter("js_patientId") != null && request.getParameter("js_token") != null)
        {
            JSONObject requestObj = new JSONObject();
            requestObj.put("tradeNo", request.getParameter("js_token"));
            requestObj.put("outTradeNo", request.getParameter("js_patientId"));
            logger.info("2、刷新用户报告" + JSON.toJSONString(anWechatUser));
            anCallBackService.refreshUserReport(requestObj);
        }
        List<AnWechatUserMechanism> anWechatUserMechanisms = anWechatUserMechanismService.selectAnWechatUserMechanismList(queryAnWechatUserMechanism);
        JSONObject reportObj = null;
        for (AnWechatUserMechanism anWechatUserMechanism : anWechatUserMechanisms)
        {
            if (anWechatUserMechanism.getScreeningResult() == null)
            {
                JSONObject requestObj = new JSONObject();
                requestObj.put("tradeNo", anWechatUserMechanism.getTradeNo());
                requestObj.put("outTradeNo", anWechatUserMechanism.getOutTradeNo());
                anCallBackService.refreshUserReport(requestObj);
            }
        }
        anWechatUserMechanisms = anWechatUserMechanismService.selectWechatUserMechanismByWechatUserIds(Collections.singletonList(anWechatUser.getWechatUserId()));
        for (AnWechatUserMechanism anWechatUserMechanism : anWechatUserMechanisms)
        {
            if (anWechatUserMechanism.getScreeningResult() != null)
            {
                reportObj = JSONObject.parseObject(anWechatUserMechanism.getScreeningResult());
                if (reportObj.getInteger("code") != 1)
                {
                    return AjaxResult.error("报告不存在！");
                } else
                {
                    reportObj.getJSONObject("data").put("gender", anWechatUser.getSex() == 0 ? "男" : "女");
                    reportObj.put("mechanismMemberUserId", anWechatUserMechanism.getMechanismMemberUserId());
                }
                break;
            }
        }
        if (reportObj == null)
        {
            List<AnWechatUserMechanism> lstReport = anWechatUserMechanismService.selectWechatUserReport(anWechatUser.getWechatUserId());
            logger.info("报告为空时查询用户报告" + JSON.toJSONString(lstReport));
            if (lstReport.size() > 0)
            {
                reportObj = JSONObject.parseObject(lstReport.get(0).getScreeningResult());
            }
        }
        if (reportObj == null)
        {
           logger.info("查询报告为空！" + JSON.toJSONString(reportObj));
           return AjaxResult.error(800,"查询报告为空！");
        }
        logger.info("3、返回用户报告" + JSON.toJSONString(reportObj));
        return AjaxResult.success(reportObj);
    }

    /**
     * 查询用户报告
     */
    @PostMapping("/wechat_user/report/bind_img")
    public AjaxResult userReport(@RequestBody JSONObject requestObj) {
        Long mechanismMemberUserId = requestObj.getLong("mechanismMemberUserId");
        String screeningImg = requestObj.getString("screeningImg");
        AnWechatUserMechanism anWechatUserMechanism = anWechatUserMechanismService.selectAnWechatUserMechanismByMechanismMemberUserId(mechanismMemberUserId);
        anWechatUserMechanism.setScreeningImg(screeningImg);
        anWechatUserMechanismService.updateAnWechatUserMechanism(anWechatUserMechanism);
        return AjaxResult.success();
    }

    /**
     * 提交机构审核
     *
     * @param request
     * @return
     */
    @PostMapping("/mechanism/submit")
    public AjaxResult mechanismSubmit(HttpServletRequest request, @Validated @RequestBody AnMechanism anMechanism) {
        AnMechanism queryTempAnMechanism = new AnMechanism();
        queryTempAnMechanism.setMechanismName(anMechanism.getMechanismName());
        List<AnMechanism> anMechanismList = anMechanismService.selectAnMechanismList(queryTempAnMechanism);
        if (anMechanismList.size() > 0) {
            return AjaxResult.error("该机构名称已存在！");
        }
        AnWechatUser anWechatUser = CommonUtils.getAnWechatUser(request);
        anMechanism.setWechatUserId(anWechatUser.getWechatUserId());
        AnMechanism queryAnMechanism = new AnMechanism();
        queryAnMechanism.setWechatUserId(anWechatUser.getWechatUserId());
        List<AnMechanism> list = anMechanismService.selectAnMechanismList(queryAnMechanism);
        if (list.size() > 0) {
            for (AnMechanism mechanism : list) {
                anMechanismService.deleteAnMechanismByMechanismId(mechanism.getMechanismId());
            }
        }
        anMechanism.setWechatUserId(anWechatUser.getWechatUserId());
        anMechanism.setExamineStatus(0L);
        anMechanism.setApplyTime(DateUtils.getNowDate());
        anMechanism.setCreateBy("admin");
        anMechanism.setCreateTime(DateUtils.getNowDate());
        int insertAnMechanism = anMechanismService.insertAnMechanism(anMechanism);
        return AjaxResult.success(insertAnMechanism);
    }


    /**
     * 机构生成推广二维码
     *
     * @param request
     * @return
     */
    @PostMapping("/mechanism/create_qr_code")
    public AjaxResult createQrCode(HttpServletRequest request, @RequestBody AnMechanismMember anMechanismMember) {
        AnWechatUser anWechatUser = CommonUtils.getAnWechatUser(request);
        AnMechanism anMechanism = new AnMechanism();
        anMechanism.setWechatUserId(anWechatUser.getWechatUserId());
        List<AnMechanism> anMechanisms = anMechanismService.selectAnMechanismList(anMechanism);
        for (AnMechanism mechanism : anMechanisms) {
            anMechanismMember.setMechanismId(mechanism.getMechanismId());
            AnMechanismMember qrCode = anMechanismMemberService.createQrCode(anMechanismMember);
            if (qrCode == null) {
                return AjaxResult.error("该推广码已存在！");
            }
            return AjaxResult.success(qrCode);
        }
        return AjaxResult.success();
    }

    /**
     * 机构推广二维码列表
     *
     * @param request
     * @return
     */
    @GetMapping("/mechanism/qr_code/list")
    public TableDataInfo mechanismQrCodeList(HttpServletRequest request) {
        AnWechatUser anWechatUser = CommonUtils.getAnWechatUser(request);
        AnMechanism anMechanism = new AnMechanism();
        anMechanism.setWechatUserId(anWechatUser.getWechatUserId());
        List<AnMechanism> anMechanisms = anMechanismService.selectAnMechanismList(anMechanism);
        List<AnMechanismMember> members = new ArrayList<>();
        for (AnMechanism mechanism : anMechanisms) {
            AnMechanismMember anMechanismMember = new AnMechanismMember();
            anMechanismMember.setMechanismId(mechanism.getMechanismId());
            members.addAll(anMechanismMemberService.selectAnMechanismMemberList(anMechanismMember));
        }
        return getDataTable(members);
    }

    /**
     * 删除推广二维码
     *
     * @return
     */
    @DeleteMapping("/mechanism/qr_code/{mechanismMemberIds}")
    public AjaxResult removeQrCode(@PathVariable Long[] mechanismMemberIds) {
        for (Long mechanismMemberId : mechanismMemberIds) {
            AnWechatUserMechanism anMechanismMember = new AnWechatUserMechanism();
            anMechanismMember.setMechanismMemberId(mechanismMemberId);
            List<AnWechatUserMechanism> anWechatUserMechanismList = anWechatUserMechanismService.selectAnWechatUserMechanismList(anMechanismMember);
            //有推广数据的不能删除
            if (anWechatUserMechanismList.size() > 0) {
                return AjaxResult.error("该推广码下有绑定用户，无法删除！");
            }
        }
        anMechanismMemberService.deleteAnMechanismMemberByMechanismMemberIds(mechanismMemberIds);
        return success();
    }


}
